
using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

public class RootNode : NodeBase
{
    // 单例实例
    private static RootNode _instance;
    public static RootNode Instance
    {
        private set
        {
            if (_instance == null)
            {
                _instance = new RootNode();
            }
        }
        get
        {
            if (_instance == null)
            {
                _instance = new RootNode();
            }
            return _instance;
        }
    }

    // 构造函数创建RootNode实例
    private RootNode()
    {
        Tag = "RootNode";
        HasGameObject = true;
        GameObject rootObject = new GameObject("RootNode");
        Tf = rootObject.transform;
        Tf.position = Vector3.zero;
        Tf.rotation = Quaternion.identity;
        Tf.localScale = Vector3.one;
        // 添加NodeMonoBehaviour组件以支持协程和生命周期方法
        rootObject.AddComponent<NodeMonoBehaviour>();
        OnInit();
    }

    // 重写生命周期方法
    public override void OnInit()
    {
        base.OnInit();
        Log("RootNode Initialized");
    }
    public override void OnUpdate()
    {
        base.OnUpdate();
        //Log("RootNode Updating");
    }
    public override void OnLateUpdate()
    {
        base.OnLateUpdate();
        //Log("RootNode Late Updating");
    }
    public override void OnFixedUpdate()
    {
        base.OnFixedUpdate();
        //Log("RootNode Fixed Updating");
    }
    public override void OnDestroy()
    {
        if (Tf != null)
        {
            Tf.gameObject.GetComponent<MonoBehaviour>().StopAllCoroutines();
        }
        Log("RootNode Destroyed");
        _instance = null;
    }

    // 提供协程启动和停止方法
    public Coroutine StartRootCoroutine(IEnumerator routine)
    {
        if (Tf != null)
        {
            return Tf.gameObject.GetComponent<MonoBehaviour>().StartCoroutine(routine);
        }
        return null;
    }
    public void StopRootCoroutine(Coroutine routine)
    {
        if (Tf != null && routine != null)
        {
            Tf.gameObject.GetComponent<MonoBehaviour>().StopCoroutine(routine);
        }
    }
}


public class NodeMonoBehaviour : MonoBehaviour
{
    // 单例实例
    public static NodeMonoBehaviour Instance;

    private void Start()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(this.gameObject);
        }
    }

    private void Update()
    {
        RootNode.Instance?.Update();
    }
    private void LateUpdate()
    {
        RootNode.Instance?.LateUpdate();
    }
    private void FixedUpdate()
    {
        RootNode.Instance?.FixedUpdate();
    }

}
